<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 闲鱼自动回复系统</title>
    <link href="/static/lib/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="/static/lib/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <style>
        .admin-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 0;
            margin-bottom: 2rem;
        }
        .user-card {
            transition: transform 0.2s;
            border: 1px solid #e0e0e0;
        }
        .user-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .stats-card {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border: none;
        }
        .btn-danger-custom {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
            border: none;
        }
        .btn-danger-custom:hover {
            background: linear-gradient(135deg, #ee5a52 0%, #ff6b6b 100%);
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-robot"></i> 闲鱼自动回复系统
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="/">
                    <i class="bi bi-house"></i> 首页
                </a>
                <a class="nav-link active" href="/user_management.html">
                    <i class="bi bi-people"></i> 用户管理
                </a>
                <a class="nav-link" href="/data_management.html">
                    <i class="bi bi-database"></i> 数据管理
                </a>
                <a class="nav-link" href="/log_management.html">
                    <i class="bi bi-file-text"></i> 日志管理
                </a>
                <a class="nav-link" href="#" onclick="logout()">
                    <i class="bi bi-box-arrow-right"></i> 退出
                </a>
            </div>
        </div>
    </nav>

    <!-- 管理员标题 -->
    <div class="admin-header">
        <div class="container">
            <h1 class="mb-0">
                <i class="bi bi-people"></i> 用户管理
            </h1>
            <p class="mb-0 mt-2">管理系统中的所有用户账号</p>
        </div>
    </div>

    <div class="container">
        <!-- 统计信息 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <h3 id="totalUsers">-</h3>
                        <p class="mb-0">总用户数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h3 id="totalCookies">-</h3>
                        <p class="mb-0">总Cookie数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h3 id="totalCards">-</h3>
                        <p class="mb-0">总卡券数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <h3 id="systemUptime">运行中</h3>
                        <p class="mb-0">系统状态</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 用户列表 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-people-fill"></i> 用户列表
                </h5>
                <div class="d-flex gap-2">
                    <button class="btn btn-warning" onclick="showRolePermissionModal()">
                        <i class="bi bi-shield"></i> 角色权限管理
                    </button>
                    <button class="btn btn-success" onclick="showAddUserModal()">
                        <i class="bi bi-person-plus"></i> 添加用户
                    </button>
                    <button class="btn btn-primary" onclick="refreshUsers()">
                        <i class="bi bi-arrow-clockwise"></i> 刷新
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="loadingUsers" class="text-center py-4">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在加载用户信息...</p>
                </div>
                
                <!-- 用户表格 -->
                <div id="usersTable" style="display: none;">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th><i class="bi bi-person-circle me-1"></i>用户</th>
                                    <th><i class="bi bi-envelope me-1"></i>邮箱</th>
                                    <th><i class="bi bi-shield me-1"></i>类型</th>
                                    <th><i class="bi bi-tags me-1"></i>角色</th>
                                    <th><i class="bi bi-cookie me-1"></i>Cookie数</th>
                                    <th><i class="bi bi-credit-card me-1"></i>卡券数</th>
                                    <th><i class="bi bi-calendar me-1"></i>注册时间</th>
                                    <th><i class="bi bi-gear me-1"></i>操作</th>
                                </tr>
                            </thead>
                            <tbody id="usersTableBody">
                                <!-- 用户数据将在这里动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div id="noUsers" class="text-center py-4" style="display: none;">
                    <i class="bi bi-people" style="font-size: 3rem; color: #ccc;"></i>
                    <p class="mt-2 text-muted">暂无用户</p>
                    <button class="btn btn-success" onclick="showAddUserModal()">
                        <i class="bi bi-person-plus"></i> 添加第一个用户
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-exclamation-triangle text-warning"></i> 确认删除
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除用户 <strong id="deleteUserName"></strong> 吗？</p>
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle"></i>
                        <strong>警告：</strong>此操作将删除该用户的所有数据，包括：
                        <ul class="mt-2 mb-0">
                            <li>所有Cookie账号</li>
                            <li>所有卡券</li>
                            <li>所有关键字和回复设置</li>
                            <li>所有个人设置</li>
                        </ul>
                        <p class="mt-2 mb-0"><strong>此操作不可恢复！</strong></p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger-custom" onclick="confirmDeleteUser()">
                        <i class="bi bi-trash"></i> 确认删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-person-plus text-success"></i> 添加用户
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm">
                        <div class="mb-3">
                            <label for="newUsername" class="form-label">
                                <i class="bi bi-person me-1"></i>用户名 <span class="text-danger">*</span>
                            </label>
                            <input type="text" class="form-control" id="newUsername" 
                                   placeholder="3-20个字符，支持字母、数字、下划线" 
                                   required>
                            <div class="form-text">用户名不可重复，创建后不可修改</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="newEmail" class="form-label">
                                <i class="bi bi-envelope me-1"></i>邮箱地址 <span class="text-danger">*</span>
                            </label>
                            <input type="email" class="form-control" id="newEmail" 
                                   placeholder="用于接收重要通知" 
                                   required>
                            <div class="form-text">邮箱地址不可重复</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="newPassword" class="form-label">
                                <i class="bi bi-key me-1"></i>密码 <span class="text-danger">*</span>
                            </label>
                            <input type="password" class="form-control" id="newPassword" 
                                   placeholder="至少 6 个字符" 
                                   required>
                            <div class="form-text">密码长度至少 6 个字符</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="confirmPassword" class="form-label">
                                <i class="bi bi-key me-1"></i>确认密码 <span class="text-danger">*</span>
                            </label>
                            <input type="password" class="form-control" id="confirmPassword" 
                                   placeholder="再次输入密码" 
                                   required>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle"></i>
                            <strong>提示：</strong>管理员创建的用户无需邮箱验证，可直接登录使用。
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-success" onclick="createUser()">
                        <i class="bi bi-check"></i> 创建用户
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 角色管理模态框 -->
    <div class="modal fade" id="roleManagementModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-tags text-primary"></i> 管理用户角色
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <h6>用户信息</h6>
                        <div class="d-flex align-items-center p-2 bg-light rounded">
                            <i class="bi bi-person-circle me-2 text-primary"></i>
                            <span id="roleManageUserName" class="fw-bold"></span>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <h6>当前角色</h6>
                        <div id="currentRolesList" class="mb-2">
                            <!-- 当前角色将在这里显示 -->
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <h6>可分配角色</h6>
                        <div id="availableRolesList">
                            <!-- 可分配角色将在这里显示 -->
                        </div>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i>
                        <strong>说明：</strong>角色决定用户可以访问的功能模块和菜单项。一个用户可以拥有多个角色。
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveUserRoles()">
                        <i class="bi bi-check"></i> 保存角色
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 角色权限管理模态框 -->
    <div class="modal fade" id="rolePermissionModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-shield text-warning"></i> 角色权限管理
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <!-- 角色列表 -->
                        <div class="col-md-4">
                            <h6>角色列表</h6>
                            <div class="list-group" id="rolesList">
                                <!-- 角色列表将在这里显示 -->
                            </div>
                        </div>
                        
                        <!-- 权限配置 -->
                        <div class="col-md-4">
                            <h6>权限配置</h6>
                            <div id="permissionsList">
                                <!-- 权限列表将在这里显示 -->
                            </div>
                        </div>
                        
                        <!-- 菜单配置 -->
                        <div class="col-md-4">
                            <h6>菜单配置</h6>
                            <div id="menusList">
                                <!-- 菜单列表将在这里显示 -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="saveRolePermissions()">
                        <i class="bi bi-check"></i> 保存配置
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 聚合豆管理模态框 -->
    <div class="modal fade" id="balanceManagementModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-coin text-warning"></i> 聚合豆管理
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <h6>用户信息</h6>
                        <div class="d-flex align-items-center p-2 bg-light rounded">
                            <i class="bi bi-person-circle me-2 text-primary"></i>
                            <span id="balanceManageUserName" class="fw-bold"></span>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <h6>当前余额</h6>
                        <div class="d-flex align-items-center p-2 bg-warning bg-opacity-10 rounded">
                            <i class="bi bi-coin me-2 text-warning"></i>
                            <span id="currentUserBalance" class="fw-bold text-warning">0.00</span> 聚合豆
                        </div>
                    </div>
                    
                    <form id="balanceAdjustForm">
                        <div class="mb-3">
                            <label for="balanceOperation" class="form-label">操作类型</label>
                            <select class="form-select" id="balanceOperation" required>
                                <option value="">请选择操作类型</option>
                                <option value="add">充值</option>
                                <option value="subtract">扣除</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="balanceAmount" class="form-label">金额</label>
                            <div class="input-group">
                                <input type="number" class="form-control" id="balanceAmount" 
                                       min="0.01" step="0.01" placeholder="请输入金额" required>
                                <span class="input-group-text">聚合豆</span>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="balanceReason" class="form-label">操作原因</label>
                            <textarea class="form-control" id="balanceReason" rows="3" 
                                      placeholder="请输入操作原因（可选）"></textarea>
                        </div>
                        
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle"></i>
                            <strong>注意：</strong>此操作会立即生效并记录到系统日志中，请谨慎操作。
                        </div>
                        
                        <!-- 操作进度提示 -->
                        <div id="balanceOperationProgress" class="alert alert-info d-none">
                            <div class="d-flex align-items-center">
                                <div class="spinner-border spinner-border-sm me-2" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <span>正在处理操作，请稍候...</span>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-warning" onclick="adjustUserBalance()">
                        <i class="bi bi-check"></i> 确认操作
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/lib/bootstrap/bootstrap.bundle.min.js"></script>
    <script>
        let currentDeleteUserId = null;
        let deleteUserModal = null;
        let addUserModal = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查管理员权限
            checkAdminPermission();
            
            // 初始化模态框
            deleteUserModal = new bootstrap.Modal(document.getElementById('deleteUserModal'));
            addUserModal = new bootstrap.Modal(document.getElementById('addUserModal'));
            balanceManagementModal = new bootstrap.Modal(document.getElementById('balanceManagementModal'));
            
            // 监听模态框关闭事件，重置所有状态
            document.getElementById('balanceManagementModal').addEventListener('hidden.bs.modal', function() {
                console.log('=== 模态框关闭，重置状态 ===');
                
                // 重置确认按钮
                const confirmButton = document.querySelector('#balanceManagementModal .btn-warning, #balanceManagementModal .btn-success');
                if (confirmButton) {
                    confirmButton.innerHTML = '<i class="bi bi-check"></i> 确认操作';
                    confirmButton.className = 'btn btn-warning';
                    confirmButton.disabled = false;
                    confirmButton.style.display = '';
                }
                
                // 重置表单
                document.getElementById('balanceAdjustForm').reset();
                
                // 重置进度提示
                const progressDiv = document.getElementById('balanceOperationProgress');
                if (progressDiv) {
                    progressDiv.className = 'alert alert-info d-none';
                    progressDiv.innerHTML = `
                        <div class="d-flex align-items-center">
                            <div class="spinner-border spinner-border-sm me-2" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <span>正在处理操作，请稍候...</span>
                        </div>
                    `;
                }
            });
            
            // 加载数据
            loadSystemStats();
            loadUsers();
        });

        // 检查管理员权限
        function checkAdminPermission() {
            const token = localStorage.getItem('auth_token');
            if (!token) {
                alert('请先登录');
                window.location.href = '/login.html';
                return;
            }

            // 验证token并检查是否为管理员
            fetch('/verify', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                if (!data.authenticated) {
                    alert('登录已过期，请重新登录');
                    window.location.href = '/login.html';
                    return;
                }
                
                // 检查是否为管理员
                if (data.username !== 'admin') {
                    alert('此功能仅限管理员使用');
                    window.location.href = '/';
                    return;
                }
            })
            .catch(error => {
                console.error('权限验证失败:', error);
                alert('权限验证失败');
                window.location.href = '/login.html';
            });
        }

        // 加载系统统计信息
        function loadSystemStats() {
            const token = localStorage.getItem('auth_token');
            
            fetch('/admin/stats', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('totalUsers').textContent = data.users.total;
                document.getElementById('totalCookies').textContent = data.cookies.total;
                document.getElementById('totalCards').textContent = data.cards.total;
            })
            .catch(error => {
                console.error('加载统计信息失败:', error);
            });
        }

        // 加载用户列表
        function loadUsers() {
            const token = localStorage.getItem('auth_token');
            const loadingDiv = document.getElementById('loadingUsers');
            const usersTableDiv = document.getElementById('usersTable');
            const noUsersDiv = document.getElementById('noUsers');
            
            loadingDiv.style.display = 'block';
            usersTableDiv.style.display = 'none';
            noUsersDiv.style.display = 'none';
            
            fetch('/admin/users', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                loadingDiv.style.display = 'none';
                
                if (data.users && data.users.length > 0) {
                    displayUsersTable(data.users);
                    usersTableDiv.style.display = 'block';
                } else {
                    noUsersDiv.style.display = 'block';
                }
            })
            .catch(error => {
                console.error('加载用户列表失败:', error);
                loadingDiv.style.display = 'none';
                noUsersDiv.style.display = 'block';
                alert('加载用户列表失败');
            });
        }

        // 显示用户表格
        function displayUsersTable(users) {
            const tableBody = document.getElementById('usersTableBody');
            tableBody.innerHTML = '';
            
            users.forEach(user => {
                const row = createUserTableRow(user);
                tableBody.appendChild(row);
            });
        }

        // 创建用户表格行
        function createUserTableRow(user) {
            const row = document.createElement('tr');
            const isAdmin = user.username === 'admin';
            
            // 格式化角色显示
            const rolesBadges = user.roles && user.roles.length > 0 
                ? user.roles.map(role => `<span class="badge bg-secondary me-1">${role.name}</span>`).join('')
                : '<span class="text-muted">无角色</span>';
            
            row.innerHTML = `
                <td>
                    <div class="d-flex align-items-center">
                        <i class="bi bi-person-circle me-2 text-primary"></i>
                        <div>
                            <div class="fw-bold">${user.username}</div>
                            <small class="text-muted">${isAdmin ? '管理员' : '普通用户'}</small>
                        </div>
                    </div>
                </td>
                <td>
                    <i class="bi bi-envelope me-1 text-muted"></i>
                    ${user.email}
                </td>
                <td>
                    <span class="badge ${isAdmin ? 'bg-danger' : 'bg-primary'}">
                        <i class="bi bi-${isAdmin ? 'shield-check' : 'person'} me-1"></i>
                        ${isAdmin ? '管理员' : '普通用户'}
                    </span>
                </td>
                <td>
                    <div class="d-flex flex-wrap gap-1">
                        ${rolesBadges}
                    </div>
                </td>
                <td>
                    <span class="badge bg-info">${user.cookie_count || 0}</span>
                </td>
                <td>
                    <span class="badge bg-success">${user.card_count || 0}</span>
                </td>
                <td>
                    <small class="text-muted">${formatDate(user.created_at)}</small>
                </td>
                <td>
                    <div class="btn-group btn-group-sm" role="group">
                        <button class="btn btn-outline-warning" onclick="manageUserBalance(${user.id}, '${user.username}')" title="管理聚合豆">
                            <i class="bi bi-coin"></i>
                        </button>
                        <button class="btn btn-outline-primary" onclick="manageUserRoles(${user.id}, '${user.username}')" title="管理角色">
                            <i class="bi bi-tags"></i>
                        </button>
                        ${!isAdmin ? `
                            <button class="btn btn-outline-danger" onclick="deleteUser(${user.id}, '${user.username}')" title="删除用户">
                                <i class="bi bi-trash"></i>
                            </button>
                        ` : `
                            <button class="btn btn-outline-secondary" disabled title="管理员不可删除">
                                <i class="bi bi-shield-check"></i>
                            </button>
                        `}
                    </div>
                </td>
            `;
            
            return row;
        }

        // 显示添加用户模态框
        function showAddUserModal() {
            // 清空表单
            document.getElementById('addUserForm').reset();
            // 显示模态框
            addUserModal.show();
        }

        // 创建用户
        function createUser() {
            const username = document.getElementById('newUsername').value.trim();
            const email = document.getElementById('newEmail').value.trim();
            const password = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            // 验证输入
            if (!username || !email || !password || !confirmPassword) {
                alert('请填写所有必填字段');
                return;
            }
            
            if (username.length < 3 || username.length > 20) {
                alert('用户名长度必须在3-20个字符之间');
                return;
            }
            
            if (!/^[a-zA-Z0-9_]+$/.test(username)) {
                alert('用户名只能包含字母、数字和下划线');
                return;
            }
            
            if (password.length < 6) {
                alert('密码长度至少6个字符');
                return;
            }
            
            if (password !== confirmPassword) {
                alert('密码和确认密码不一致');
                return;
            }
            
            const token = localStorage.getItem('auth_token');
            
            // 发送创建请求
            fetch('/admin/users', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    email: email,
                    password: password
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    addUserModal.hide();
                    alert(data.message || '用户创建成功');
                    
                    // 刷新页面数据
                    loadSystemStats();
                    loadUsers();
                } else {
                    alert(data.message || '用户创建失败');
                }
            })
            .catch(error => {
                console.error('创建用户失败:', error);
                alert('创建用户失败');
            });
        }

        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN');
        }

        // 删除用户
        function deleteUser(userId, username) {
            currentDeleteUserId = userId;
            document.getElementById('deleteUserName').textContent = username;
            deleteUserModal.show();
        }

        // 确认删除用户
        function confirmDeleteUser() {
            if (!currentDeleteUserId) return;

            const token = localStorage.getItem('auth_token');
            
            fetch(`/admin/users/${currentDeleteUserId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                deleteUserModal.hide();
                alert(data.message || '用户删除成功');
                
                // 刷新页面数据
                loadSystemStats();
                loadUsers();
            })
            .catch(error => {
                console.error('删除用户失败:', error);
                alert('删除用户失败');
            });
        }

        // 刷新用户列表
        function refreshUsers() {
            loadSystemStats();
            loadUsers();
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('auth_token');
            window.location.href = '/login.html';
        }

        // ==================== 角色管理功能 ====================
        
        let currentManageUserId = null;
        let roleManagementModal = null;
        let rolePermissionModal = null;
        let currentSelectedRoleId = null;
        let allRoles = [];
        let allPermissions = [];
        let allMenus = [];

        // 初始化角色管理模态框
        document.addEventListener('DOMContentLoaded', function() {
            roleManagementModal = new bootstrap.Modal(document.getElementById('roleManagementModal'));
            rolePermissionModal = new bootstrap.Modal(document.getElementById('rolePermissionModal'));
        });

        // 管理用户角色
        async function manageUserRoles(userId, username) {
            currentManageUserId = userId;
            document.getElementById('roleManageUserName').textContent = username;
            
            try {
                // 加载所有角色
                await loadAllRoles();
                
                // 获取用户当前角色
                const token = localStorage.getItem('auth_token');
                const response = await fetch(`/admin/users`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                const data = await response.json();
                
                const user = data.users.find(u => u.id === userId);
                const userRoles = user ? user.roles : [];
                
                // 显示当前角色
                displayCurrentRoles(userRoles);
                
                // 显示可分配角色
                displayAvailableRoles(userRoles);
                
                // 显示模态框
                roleManagementModal.show();
            } catch (error) {
                console.error('加载角色信息失败:', error);
                alert('加载角色信息失败');
            }
        }

        // 显示当前角色
        function displayCurrentRoles(userRoles) {
            const container = document.getElementById('currentRolesList');
            if (userRoles.length === 0) {
                container.innerHTML = '<span class="text-muted">暂无角色</span>';
                return;
            }
            
            container.innerHTML = userRoles.map(role => `
                <span class="badge bg-primary me-1 mb-1">${role.name}</span>
            `).join('');
        }

        // 显示可分配角色
        function displayAvailableRoles(userRoles) {
            const container = document.getElementById('availableRolesList');
            const userRoleIds = userRoles.map(r => r.id);
            
            container.innerHTML = allRoles.map(role => {
                const isChecked = userRoleIds.includes(role.id);
                return `
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" 
                               value="${role.id}" id="role_${role.id}" 
                               ${isChecked ? 'checked' : ''}>
                        <label class="form-check-label d-flex justify-content-between" for="role_${role.id}">
                            <div>
                                <strong>${role.name}</strong>
                                <br><small class="text-muted">${role.description}</small>
                            </div>
                            <small class="text-muted">${role.user_count || 0} 人</small>
                        </label>
                    </div>
                `;
            }).join('');
        }

        // 保存用户角色
        async function saveUserRoles() {
            const checkboxes = document.querySelectorAll('#availableRolesList input[type="checkbox"]:checked');
            const roleIds = Array.from(checkboxes).map(cb => parseInt(cb.value));
            
            try {
                const token = localStorage.getItem('auth_token');
                const response = await fetch(`/admin/users/${currentManageUserId}/roles`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ role_ids: roleIds })
                });
                
                const data = await response.json();
                if (data.success) {
                    roleManagementModal.hide();
                    alert('用户角色更新成功');
                    loadUsers(); // 刷新用户列表
                } else {
                    alert(data.message || '用户角色更新失败');
                }
            } catch (error) {
                console.error('保存用户角色失败:', error);
                alert('保存用户角色失败');
            }
        }

        // 显示角色权限管理模态框
        async function showRolePermissionModal() {
            try {
                // 加载所有数据
                await Promise.all([
                    loadAllRoles(),
                    loadAllPermissions(),
                    loadAllMenus()
                ]);
                
                // 显示角色列表
                displayRolesList();
                
                // 显示模态框
                rolePermissionModal.show();
            } catch (error) {
                console.error('加载角色权限数据失败:', error);
                alert('加载角色权限数据失败');
            }
        }

        // 加载所有角色
        async function loadAllRoles() {
            const token = localStorage.getItem('auth_token');
            const response = await fetch('/admin/roles', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            allRoles = data.roles;
        }

        // 加载所有权限
        async function loadAllPermissions() {
            const token = localStorage.getItem('auth_token');
            const response = await fetch('/admin/permissions', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            allPermissions = data.permissions;
        }

        // 加载所有菜单
        async function loadAllMenus() {
            const token = localStorage.getItem('auth_token');
            const response = await fetch('/admin/menus', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            allMenus = data.menus;
        }

        // 显示角色列表
        function displayRolesList() {
            const container = document.getElementById('rolesList');
            container.innerHTML = allRoles.map(role => `
                <a href="#" class="list-group-item list-group-item-action" 
                   onclick="selectRole(${role.id})" id="roleItem_${role.id}">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">${role.name}</h6>
                        <small class="text-muted">${role.user_count || 0} 人</small>
                    </div>
                    <p class="mb-1">${role.description}</p>
                    <small class="text-muted">
                        权限: ${role.permission_count || 0} 个 | 菜单: ${role.menu_count || 0} 个
                        ${role.is_system ? ' | <span class="badge bg-warning">系统角色</span>' : ''}
                    </small>
                </a>
            `).join('');
        }

        // 选择角色
        async function selectRole(roleId) {
            currentSelectedRoleId = roleId;
            
            // 更新选中状态
            document.querySelectorAll('#rolesList .list-group-item').forEach(item => {
                item.classList.remove('active');
            });
            document.getElementById(`roleItem_${roleId}`).classList.add('active');
            
            try {
                // 获取角色详情
                const token = localStorage.getItem('auth_token');
                const response = await fetch(`/admin/roles/${roleId}`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                const data = await response.json();
                
                // 显示权限配置
                displayPermissionsConfig(data.permissions);
                
                // 显示菜单配置
                displayMenusConfig(data.menus);
            } catch (error) {
                console.error('获取角色详情失败:', error);
                alert('获取角色详情失败');
            }
        }

        // 显示权限配置
        function displayPermissionsConfig(rolePermissions) {
            const container = document.getElementById('permissionsList');
            const rolePermissionIds = rolePermissions.map(p => p.id);
            
            // 按分类分组
            const permissionsByCategory = {};
            allPermissions.forEach(perm => {
                if (!permissionsByCategory[perm.category]) {
                    permissionsByCategory[perm.category] = [];
                }
                permissionsByCategory[perm.category].push(perm);
            });
            
            let html = '';
            Object.keys(permissionsByCategory).forEach(category => {
                html += `<h6 class="mt-3">${getCategoryName(category)}</h6>`;
                permissionsByCategory[category].forEach(permission => {
                    const isChecked = rolePermissionIds.includes(permission.id);
                    html += `
                        <div class="form-check mb-1">
                            <input class="form-check-input" type="checkbox" 
                                   value="${permission.id}" id="perm_${permission.id}" 
                                   ${isChecked ? 'checked' : ''}>
                            <label class="form-check-label" for="perm_${permission.id}">
                                <small><strong>${permission.description}</strong></small>
                            </label>
                        </div>
                    `;
                });
            });
            
            container.innerHTML = html;
        }

        // 显示菜单配置
        function displayMenusConfig(roleMenus) {
            const container = document.getElementById('menusList');
            const roleMenuIds = roleMenus.map(m => m.id);
            
            let html = '';
            allMenus.forEach(menu => {
                if (!menu.parent_id) { // 只显示顶级菜单
                    const isChecked = roleMenuIds.includes(menu.id);
                    html += `
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="checkbox" 
                                   value="${menu.id}" id="menu_${menu.id}" 
                                   ${isChecked ? 'checked' : ''}>
                            <label class="form-check-label" for="menu_${menu.id}">
                                <i class="${menu.icon} me-1"></i>
                                <strong>${menu.name}</strong>
                            </label>
                        </div>
                    `;
                    
                    // 显示子菜单
                    const subMenus = allMenus.filter(m => m.parent_id === menu.id);
                    subMenus.forEach(subMenu => {
                        const isSubChecked = roleMenuIds.includes(subMenu.id);
                        html += `
                            <div class="form-check mb-1 ms-4">
                                <input class="form-check-input" type="checkbox" 
                                       value="${subMenu.id}" id="menu_${subMenu.id}" 
                                       ${isSubChecked ? 'checked' : ''}>
                                <label class="form-check-label" for="menu_${subMenu.id}">
                                    <i class="${subMenu.icon} me-1"></i>
                                    ${subMenu.name}
                                </label>
                            </div>
                        `;
                    });
                }
            });
            
            container.innerHTML = html;
        }

        // 保存角色权限配置
        async function saveRolePermissions() {
            if (!currentSelectedRoleId) {
                alert('请先选择要配置的角色');
                return;
            }
            
            const permissionCheckboxes = document.querySelectorAll('#permissionsList input[type="checkbox"]:checked');
            const permissionIds = Array.from(permissionCheckboxes).map(cb => parseInt(cb.value));
            
            const menuCheckboxes = document.querySelectorAll('#menusList input[type="checkbox"]:checked');
            const menuIds = Array.from(menuCheckboxes).map(cb => parseInt(cb.value));
            
            try {
                const token = localStorage.getItem('auth_token');
                
                // 保存权限配置
                await fetch(`/admin/roles/${currentSelectedRoleId}/permissions`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ permission_ids: permissionIds })
                });
                
                // 保存菜单配置
                await fetch(`/admin/roles/${currentSelectedRoleId}/menus`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ menu_ids: menuIds })
                });
                
                alert('角色权限配置保存成功');
                
                // 刷新角色列表
                await loadAllRoles();
                displayRolesList();
                
            } catch (error) {
                console.error('保存角色权限配置失败:', error);
                alert('保存角色权限配置失败');
            }
        }

        // 获取分类名称
        function getCategoryName(category) {
            const categoryNames = {
                'general': '通用',
                'account': '账号管理',
                'item': '商品管理', 
                'order': '订单管理',
                'reply': '自动回复',
                'keyword': '关键词管理',
                'card': '卡种管理',
                'delivery': '发货管理',
                'notification': '通知管理',
                'search': '搜索功能',
                'system': '系统管理',
                'admin': '管理员功能'
            };
            return categoryNames[category] || category;
        }

        // ==================== 聚合豆管理功能 ====================
        
        let currentBalanceUserId = null;
        let balanceManagementModal = null;
        
        // 管理用户聚合豆
        async function manageUserBalance(userId, username) {
            currentBalanceUserId = userId;
            
            // 设置用户名
            document.getElementById('balanceManageUserName').textContent = username;
            
            try {
                // 获取用户当前余额
                const response = await fetch(`/admin/user-balance/${userId}`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    document.getElementById('currentUserBalance').textContent = result.balance.toFixed(2);
                } else {
                    document.getElementById('currentUserBalance').textContent = '0.00';
                }
                
                // 重置表单
                document.getElementById('balanceAdjustForm').reset();
                
                // 显示模态框
                balanceManagementModal.show();
            } catch (error) {
                console.error('获取用户余额失败:', error);
                showAlert('获取用户余额失败', 'danger');
            }
        }
        
        // 调整用户余额
        async function adjustUserBalance() {
            console.log('=== 开始调整用户余额 ===');
            
            const operation = document.getElementById('balanceOperation').value;
            const amount = parseFloat(document.getElementById('balanceAmount').value);
            const reason = document.getElementById('balanceReason').value;
            
            console.log('操作参数:', { operation, amount, reason, currentBalanceUserId });
            
            if (!operation) {
                showAlert('请选择操作类型', 'warning');
                return;
            }
            
            if (!amount || amount <= 0) {
                showAlert('请输入有效的金额', 'warning');
                return;
            }

            // 显示确认对话框
            const actionText = operation === 'add' ? '充值' : '扣除';
            const userName = document.getElementById('balanceManageUserName').textContent;
            const confirmMessage = `确认要为用户 "${userName}" ${actionText} ${amount.toFixed(2)} 聚合豆吗？${reason ? '\n操作原因：' + reason : ''}`;
            
            if (!confirm(confirmMessage)) {
                return;
            }
            
            try {
                // 显示加载状态
                const confirmButton = document.querySelector('#balanceManagementModal .btn-warning');
                const progressDiv = document.getElementById('balanceOperationProgress');
                const originalButtonText = confirmButton.innerHTML;
                
                confirmButton.innerHTML = '<i class="bi bi-hourglass-split"></i> 操作中...';
                confirmButton.disabled = true;
                progressDiv.classList.remove('d-none');
                
                console.log('发送API请求...');
                const response = await fetch('/admin/adjust-balance', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
                    },
                    body: JSON.stringify({
                        user_id: currentBalanceUserId,
                        operation: operation,
                        amount: amount,
                        reason: reason || '管理员操作'
                    })
                });
                
                console.log('API响应状态:', response.status);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const result = await response.json();
                console.log('=== API响应结果 ===', result);
                
                if (result.success) {
                    console.log('=== 操作成功，开始显示反馈 ===');
                    const actionText = operation === 'add' ? '充值' : '扣除';
                    const amountText = amount.toFixed(2);
                    const userName = document.getElementById('balanceManageUserName').textContent;
                    
                    // 第一步：立即显示原生alert确保用户能看到
                    alert(`🎉 聚合豆${actionText}成功！\n\n用户：${userName}\n${actionText}金额：${amountText} 聚合豆\n当前余额：${result.new_balance.toFixed(2)} 聚合豆`);
                    
                    // 第二步：更新模态框内容显示成功状态
                    const progressDiv = document.getElementById('balanceOperationProgress');
                    const confirmButton = document.querySelector('#balanceManagementModal .btn-warning');
                    
                    // 隐藏进度条，显示成功信息
                    progressDiv.innerHTML = `
                        <div class="text-center p-4">
                            <i class="bi bi-check-circle-fill text-success" style="font-size: 4rem;"></i>
                            <h3 class="mt-3 mb-3 text-success">🎉 操作成功！</h3>
                            <div class="fs-5 mb-3">
                                <div><strong>用户：</strong>${userName}</div>
                                <div><strong>${actionText}金额：</strong>${amountText} 聚合豆</div>
                                <div><strong>当前余额：</strong>${result.new_balance.toFixed(2)} 聚合豆</div>
                            </div>
                            <button type="button" class="btn btn-success" data-bs-dismiss="modal">
                                <i class="bi bi-check"></i> 确定
                            </button>
                        </div>
                    `;
                    progressDiv.className = 'alert alert-success';
                    
                    // 更新按钮状态
                    confirmButton.style.display = 'none'; // 隐藏原确认按钮
                    
                    // 第三步：更新显示的余额
                    const balanceElement = document.getElementById('currentUserBalance');
                    if (balanceElement) {
                        balanceElement.textContent = result.new_balance.toFixed(2);
                    }
                    
                    // 第四步：重置表单并刷新数据
                    document.getElementById('balanceAdjustForm').reset();
                    loadUsers();
                } else {
                    console.log('=== 操作失败 ===', result.message);
                    showAlert(`
                        <div class="text-center p-2">
                            <i class="bi bi-exclamation-triangle-fill text-danger" style="font-size: 2rem;"></i>
                            <h5 class="mt-2 text-danger">操作失败！</h5>
                            <div>${result.message || '未知错误'}</div>
                        </div>
                    `, 'danger');
                }
            } catch (error) {
                console.error('调整余额失败:', error);
                
                // 显示详细的错误信息
                showAlert(`
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    <strong>操作失败！</strong><br/>
                    <strong>错误信息：</strong>${error.message}<br/>
                    <small class="text-muted">请检查网络连接或联系管理员</small>
                `, 'danger');
                
                // 在模态框内也显示错误
                const progressDiv = document.getElementById('balanceOperationProgress');
                progressDiv.innerHTML = `
                    <div class="d-flex align-items-center">
                        <i class="bi bi-exclamation-triangle-fill text-danger me-2"></i>
                        <span class="text-danger fw-bold">操作失败：${error.message}</span>
                    </div>
                `;
                progressDiv.className = 'alert alert-danger';
                
            } finally {
                // 恢复按钮状态（仅在失败时）
                setTimeout(() => {
                    const confirmButton = document.querySelector('#balanceManagementModal .btn-warning, #balanceManagementModal .btn-success');
                    const progressDiv = document.getElementById('balanceOperationProgress');
                    if (confirmButton && !confirmButton.classList.contains('btn-success')) {
                        confirmButton.innerHTML = '<i class="bi bi-check"></i> 确认操作';
                        confirmButton.className = 'btn btn-warning';
                        confirmButton.disabled = false;
                    }
                    if (progressDiv && progressDiv.classList.contains('alert-danger')) {
                        progressDiv.classList.add('d-none');
                    }
                }, 1000);
            }
        }
        
        // 显示提示信息
        function showAlert(message, type) {
            // 移除之前的alert
            const existingAlerts = document.querySelectorAll('.alert-custom-notification');
            existingAlerts.forEach(alert => alert.remove());
            
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show alert-custom-notification`;
            alertDiv.style.cssText = `
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                z-index: 9999;
                min-width: 400px;
                max-width: 600px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                border: none;
                font-size: 16px;
            `;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            // 添加到body而不是container
            document.body.appendChild(alertDiv);
            
            // 8秒后自动消失（更长的显示时间）
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 8000);
        }

        // 播放成功音效
        function playSuccessSound() {
            try {
                // 创建音频上下文（如果浏览器支持）
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const oscillator = audioContext.createOscillator();
                const gainNode = audioContext.createGain();
                
                oscillator.connect(gainNode);
                gainNode.connect(audioContext.destination);
                
                // 设置成功音效（短促的高音）
                oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
                oscillator.frequency.setValueAtTime(1000, audioContext.currentTime + 0.1);
                
                gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
                
                oscillator.start(audioContext.currentTime);
                oscillator.stop(audioContext.currentTime + 0.2);
            } catch (e) {
                // 忽略音效错误，不影响主要功能
                console.log('音效播放失败（正常）:', e.message);
            }
        }

        // 显示成功Toast通知（更醒目的提醒）
        function showSuccessToast(message) {
            // 创建Toast容器（如果不存在）
            let toastContainer = document.getElementById('toastContainer');
            if (!toastContainer) {
                toastContainer = document.createElement('div');
                toastContainer.id = 'toastContainer';
                toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
                toastContainer.style.zIndex = '9999';
                document.body.appendChild(toastContainer);
            }

            // 创建Toast元素
            const toastId = 'toast_' + Date.now();
            const toastHTML = `
                <div id="${toastId}" class="toast align-items-center text-bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="d-flex">
                        <div class="toast-body">
                            <i class="bi bi-check-circle-fill me-2"></i>
                            ${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                </div>
            `;

            toastContainer.insertAdjacentHTML('beforeend', toastHTML);
            
            // 显示Toast
            const toastElement = document.getElementById(toastId);
            const toast = new bootstrap.Toast(toastElement, {
                autohide: true,
                delay: 4000
            });
            toast.show();

            // 清理已隐藏的Toast
            toastElement.addEventListener('hidden.bs.toast', () => {
                toastElement.remove();
            });
        }
    </script>
</body>
</html>
